package 深市_沪市;

import Utils.Tools;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DownloadPDF_1 {

    static MongoClient mongoClient = new MongoClient("192.168.1.173", 27017);
    static MongoDatabase mDatabase = mongoClient.getDatabase("巨潮网络");
    static MongoCollection collection = mDatabase.getCollection("沪市");
    static final String SAVE_PATH = "D:/测试临时文件/" + collection.getNamespace().getCollectionName() + "/";
    static Logger logger = LoggerFactory.getLogger(DownloadPDF_1.class);

    static {
        Tools.initFolder(SAVE_PATH);
    }

    public static void main(String[] args) throws InterruptedException, IOException, InvalidFormatException {
        List<Map<String, String>> downloadList = getDownloadList();

        logger.info("开始下载....");
        downloadList.forEach(map -> {
            try {
                Tools.Download(map, SAVE_PATH);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    public static List<String> getAllFileTitle(){
        /**
         * 获取所有的文件名
         */
        List<String> allFilePath = Tools.getAllFilePath(SAVE_PATH);

        List<String> allFileTitle = new ArrayList<>();
        allFilePath.forEach(filePath -> {
            allFileTitle.add(filePath.substring(SAVE_PATH.length()));
        });

        return allFileTitle;
    }

    public static List<Map<String, String>> getDownloadList(){
        /**
         * 获取下载信息
         * 已在本地的文件，不再重复下载
         */
        List<Map<String, String>> dbDownloadList = Tools.getDbDownloadInfo(collection);
        List<String> allFileTitle = getAllFileTitle();

        List<Map<String, String>> downloadList = new ArrayList<>();
        dbDownloadList.forEach(map -> {
            if (!allFileTitle.contains(map.get("title")))
                downloadList.add(map);
        });

        logger.info("获取下载信息完成！\n下载数量:" + downloadList.size());
        return downloadList;
    }

}
